//
//  KDialog.swift
//  OnemeetingDemo
//
//  Created by 张衡 on 2020/4/22.
//  Copyright © 2020 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

struct InfokDialog {
    var title:String!
    var contText:String!
    var btnTitle:String!
    var twoBtnTitle:String?
    var image:NSImage?
    init(title:String,contText:String,btnTitle:String,twoBtnTitle:String?,image:NSImage?) {
        self.title = title
        self.contText = contText
        self.btnTitle = btnTitle
        self.twoBtnTitle = twoBtnTitle
        self.image = image
    }
}


class KDialog: NSObject{
    
    static let shared = KDialog()
    
    var tapBlock:((Int)->())?
    
    class func beginSheetModal(info:InfokDialog,completionHandler handler: ((NSApplication.ModalResponse) -> Void)? = nil) {
        let alert = NSAlert.init()
        alert.addButton(withTitle: info.btnTitle)
        alert.messageText = info.title
        alert.informativeText = info.contText
        alert.alertStyle = .warning
        if info.image != nil {
            alert.icon = info.image
        }
        if info.twoBtnTitle != nil {
            alert.addButton(withTitle: info.twoBtnTitle!)
        }
        
        guard let window = NSApplication.shared.mainWindow else {
            return
        }
        alert.beginSheetModal(for: window) { (returnCode) in
            if handler != nil {
                handler!(returnCode)
            }
        }
    }
    
    lazy var alert: NSAlert = {
        let alert = NSAlert.init()
        alert.alertStyle = .warning
        return alert
    }()
    
    func runModal(info:InfokDialog) {
        
        self.alert.messageText = info.title
        self.alert.informativeText = info.contText
        if info.image != nil {
            alert.icon = info.image
        }
        if self.alert.buttons.count<1 {
            self.alert.addButton(withTitle: info.btnTitle)
        }else {
            self.alert.buttons[0].title = info.btnTitle
        }
        self.alert.buttons[0].tag = 0
        self.alert.buttons[0].target = self
        self.alert.buttons[0].action = #selector(btnAction(senber:))
        if info.twoBtnTitle != nil {
            if self.alert.buttons.count<2 {
                self.alert.addButton(withTitle: info.twoBtnTitle!)
            }else {
                self.alert.buttons[1].title = info.twoBtnTitle!
            }
            alert.buttons[1].tag = 1
            alert.buttons[1].target = self
            alert.buttons[1].action = #selector(btnAction(senber:))
        }
        alert.runModal()
        
    }
    
    @objc func btnAction(senber:NSButton) {
        print(senber.tag)
        if tapBlock != nil {
            self.tapBlock!(senber.tag)
        }
    }
    
    func close()  {
        NSApp.endSheet(self.alert.window)
        self.alert.window.orderOut(self)
    }
}
